package www.qiyue.thread;

import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.concurrent.*;
@Slf4j
public class ThreadTest {

    private static ExecutorService executorService = new ThreadPoolExecutor(1, 50,1, TimeUnit.MINUTES, new LinkedBlockingQueue<>(10000), Executors.defaultThreadFactory(), new CustomRejectedExecutionHandler());
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ArrayList<String> arrayList = new ArrayList<>();
        CompletableFuture<BigDecimal> bigDecimalFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("开始了 = ");
            return getByNumber();
        }, executorService).handle((t, u) -> {
            if (u!=null){
                log.error("异常有问题"+u);
            }
            return new BigDecimal("0");
        });
        CompletableFuture<Void> future02 = bigDecimalFuture.thenAcceptAsync(res -> {
            arrayList.add("future02");
            throw new RuntimeException();

        }, executorService).whenComplete((t, u) -> {
            if (u!=null){
                log.error("future02有问题"+u);
            }
        });
        CompletableFuture<Void> future03 = bigDecimalFuture.thenAcceptAsync(res -> {
            double v = res.doubleValue() / 5;
            arrayList.add("future03"+v);
        }, executorService).whenComplete((t, u) -> {
            if (u!=null){
                log.error("future03有问题"+u);
            }
        });

        CompletableFuture<Void> future04 = CompletableFuture.runAsync(() -> {
            arrayList.add("future04");
        }, executorService).whenComplete((t, u) -> {
            if (u!=null){
                log.error("future04异常信息"+u);
            }
        });
         CompletableFuture.allOf(future02, future03, future04).get();

        System.out.println("arrayList = " + arrayList);

    }
    private static class CustomRejectedExecutionHandler implements RejectedExecutionHandler {

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            // 记录异常
            System.out.println(r);
            // 报警处理等
            System.out.println("error............."+executor);
        }
    }
    private static BigDecimal getByNumber(){
        return new BigDecimal("10");
    }
}
